import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import { List, AutoSizer } from 'react-virtualized'

import { getCityList, getHotCityList } from '../../network/citylist'
import { getCurrCity } from '../../utils'
import './index.scss'
import NavHeader from '../../components/Common/NavHeader'

const TITLE_HEIGHT = 36
const NAME_HEIGHT = 50
const HOUSE_CITY = ['上海', '北京', '广州', '深圳']
// 处理城市索引
const handleCityLetter = (letter) => {
  switch (letter) {
    case '#':
      return '当前定位'
    case 'hot':
      return '热门城市'
    default:
      return letter.toUpperCase()
  }
}

export default class Home extends Component {
  state = { cityList: {}, cityIndex: [], activeIndex: 0 }
  listComponent = React.createRef()

  async componentDidMount() {
    await this.getCityList()

    // 预计算页面高度
    this.listComponent.current.measureAllRows()
  }

  // 获取城市列表数据
  getCityList = async () => {
    let res = await getCityList('/area/city', 1)
    const { cityIndex, cityList } = this.formatCityList(res.body)

    res = await getHotCityList()
    const hotCityList = res.body

    // 添加热门城市
    cityList['hot'] = hotCityList
    cityIndex.unshift('hot')

    // 添加本地城市
    cityList['#'] = [await getCurrCity()]
    cityIndex.unshift('#')

    this.setState({ cityList, cityIndex })
  }

  // 处理城市列表数据
  formatCityList(list) {
    const cityList = {}
    // 处理数据
    list.forEach(item => {
      const first = item.short[0]

      if (cityList.hasOwnProperty(first)) {
        cityList[first].push(item)
      } else {
        cityList[first] = [item]
      }

    })
    const cityIndex = Object.keys(cityList).sort()
    return {
      cityList,
      cityIndex
    }
  }

  // 渲染城市列表
  rowRenderer = ({ key, index, isScrolling, isVisible, style, }) => {
    const { cityIndex, cityList } = this.state
    const letter = handleCityLetter(cityIndex[index])
    const citys = cityList[cityIndex[index]]
    return (
      <div key={key} style={style} className='city'>
        <div className="title">{letter}</div>
        {citys.map(item =>
          <div onClick={() => this.changeCity(item)} className="name" key={item.value}>
            {item.label}
          </div>)}
      </div>
    )
  }

  // 计算每行的高度
  getRowHeight = ({ index }) => {
    const { cityIndex, cityList } = this.state
    return TITLE_HEIGHT + NAME_HEIGHT * (cityList[cityIndex[index]].length)
  }

  // 渲染索引导航列表
  renderIndexList = () => {
    const { cityIndex, activeIndex } = this.state
    return cityIndex.map((item, index) => {
      return (
        <li
          className="city-index-item"
          key={item}
          onClick={() => this.listComponent.current.scrollToRow(index)}
        >
          <span className={index === activeIndex ? 'index-active' : ''}>
            {item === 'hot' ? '热' : item.toUpperCase()}
          </span>
        </li>
      )
    })
  }

  // 监听页面滚动
  onRowsRendered = ({ startIndex }) => {
    if (this.state.activeIndex !== startIndex) {
      this.setState({ activeIndex: startIndex })
    }
  }

  // 处理选择城市
  changeCity = ({ label, value }) => {
    if (HOUSE_CITY.includes(label)) {
      localStorage.setItem('hkzf_city', JSON.stringify({ label, value }))
      this.props.history.go(-1)
    } else {
      Toast.info('暂无房源，请重新选择', 2, null, false)
    }
  }
  render() {
    return (
      <div className="city-list">
        {/* 顶部导航栏 */}
        <NavHeader>城市列表</NavHeader>

        {/* 城市列表 */}
        <AutoSizer>
          {({ height, width }) => (
            <List
              ref={this.listComponent}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.getRowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>,

        {/* 字母导航栏 */}
        <ul className="city-index" >
          {this.renderIndexList()}
        </ul>
      </div >
    )
  }
}
